package com.heima.item.handler;

import com.alibaba.fastjson.JSON;
import com.heima.item.pojo.Item;
import com.heima.item.pojo.ItemStock;
import com.heima.item.service.IItemService;
import com.heima.item.service.IItemStockService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: itheima
 * @create: 2022-05-03 14:14
 */
@Component
public class RedisHandler implements InitializingBean {

    @Autowired
    private IItemService iItemService;

    @Autowired
    private IItemStockService stockService;


    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 1.查询数据库中商品列表以及库存  2.将商品库存缓存到redis中
     * 所有IOC容器对象创建完成后，执行初始化方法
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("提前将商品数据-缓存预热");
        //1.查询商品信息
        List<Item> itemList = iItemService.list();
        //2.将商品信息存入redis
        if (!CollectionUtils.isEmpty(itemList)) {
            for (Item item : itemList) {
                //商品对象转为JSON存入redis
                String jsonString = JSON.toJSONString(item);
                redisTemplate.opsForValue().set("item:id:" + item.getId(), jsonString);
            }
        }

        //3.查询库存信息
        List<ItemStock> stockList = stockService.list();
        if (!CollectionUtils.isEmpty(stockList)) {
            //4.将库存信息存入redis
            for (ItemStock itemStock : stockList) {
                String jsonString = JSON.toJSONString(itemStock);
                redisTemplate.opsForValue().set("item:stock:id:" + itemStock.getId(), jsonString);
            }
        }
    }

    /**
     * 保存数据到redis中
     *
     * @param item
     */
    public void saveItem(Item item) {
        String jsonString = JSON.toJSONString(item);
        redisTemplate.opsForValue().set("item:id:" + item.getId(), jsonString);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(Long id) {
        redisTemplate.delete("item:id:" + id);
    }
}
